/*
* @Author: Administrator
* @Date:   2017-12-23 15:54:49
* @Last Modified by:   Administrator
* @Last Modified time: 2017-12-23 16:03:35
*/
import { observable, action, computed } from 'mobx'
import { userUrl, userRegistUrl, logoutUrl } from '../util/constant'
import { post } from '../util/comm'

class User {
  constructor(userInfo) {
    this.userInfo = userInfo
  }
  @observable userInfo
  @action doLogin(param) {
    return new Promise((resolve, reject) => {
      post(userUrl, param).then((res) => {
        if (res.status === 200 && res.data.code === 1) {
          this.userInfo = res.data.data
          resolve(res.data)
        } else {
          reject(res.data.data)
        }
      }).catch(reject)
    })
  }
  @action doRegist(param) {
    // 注册api地址
    const url = userRegistUrl
    // 注册参数
    const params = {
      username: param.r_username,
      password: param.r_password,
      email: param.r_eamil,
      phone: param.r_phone,
      name: param.r_name,
    }
    return new Promise((resolve, reject) => {
      post(url, params)
        .then((res) => {
          if (res.status === 200 && res.data.code === 1) {
            resolve(res.data)
          } else {
            reject(res.data.message)
          }
        }).catch(e => reject(e))
    })
  }
  @action doLogout() {
    return new Promise((resolve, reject) => {
      post(logoutUrl).then((res) => {
        if (res.status === 200 && res.data.code === 1) {
          this.userInfo = {}
          resolve(res.data)
        } else {
          reject(res.data.data)
        }
      }).catch(reject)
    })
  }
  @computed get isLogin() {
    return (!!this.userInfo) && (!!this.userInfo.nickName)
  }
  @action clearUserInfo() {
    this.userInfo = {}
  }
}
export default User
